<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------

namespace app\api\logic;

use app\common\logic\LogicBase;
use \tpfcore\Core;
use think\Validate;
use think\Request;

class ApiBase extends LogicBase
{
	public function api_init($data=[]){
		header("Access-Control-Allow-Origin: * ");
		header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
		header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept,Access-Token,Auth-Token,Timestamp");
		$request = Request::instance();

		$config = config("config.mimi_program")['config'];
		$timestamp = $request->header("Timestamp");

		if(empty($timestamp) || (!empty($config['api_time_limit']) && is_numeric($config['api_time_limit']) && time()-$timestamp>$config['api_time_limit'])){
			return [-1,"请求失效"];
		}

		// 网页认证，目前用于微信公众号
		if(empty($request->header("Access-Token")) && !empty($config['api_ip_authorize']) && !in_array($request->ip(), explode("\n", $config['api_ip_authorize']))){
			return [-1,"ip非法"];
		}
		// 小程序验证，目前用于微信小程序、百度小程序
		else if(isset($config['mini_api_validate']) && $config['mini_api_validate']==1 && !empty($request->header("Access-Token"))){
			if(empty($config['apiKey'])){
				return [-4,"请先配置好apiKey"];
			}
			$access_token = $request->header("Access-Token");
			

			if(empty($access_token) || empty($timestamp)){
				return [-1,"非法请求"];
			}

			if(!empty($config['api_time_limit']) && is_numeric($config['api_time_limit']) && time()-$timestamp>$config['api_time_limit']){
				return [-1,"请求失效"];
			}

			if($access_token!=md5($config['apiKey'].$timestamp).md5($timestamp)){
				return [-1,"非法请求"];
			}
		}else{

		}

    	// 基础数据验证
		$validate=\think\Loader::validate("ApiBase");
        $validate_result = $validate->scene('apiBase')->check($data);
        if (!$validate_result) {
            return [-1, $validate->getError()];
        }
    }
    //  通过Auth-token获取用户信息
	public function getBaseUserInfo(){
		$request = Request::instance();
        return Core::loadModel("User")->getOneObject(["token"=>$request->header("Auth-Token")],"id,nickname");
	}
}